package com.siyao.redvip.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.siyao.redvip.components.imagepicker.activity.ImageBrowserActivity;
import com.siyao.redvip.components.imagepicker.recevier.EditImageReciver;
import com.siyao.redvip.service.NewVersionUpdateService;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

public class AppUtils {
	public static boolean checkPhone(String phoneNum) {
		 if (!TextUtils.isEmpty(phoneNum)  && phoneNum.length()  > 6) {
	            return true;
	        }
	        return false;
	}
	
    public static boolean isSDUseable() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }
    
    /**
     * 下载更新App
     * @param context
     * @param url
     */
    public static void downloadApk(Context context, String url) {
        Intent intent = new Intent(context, NewVersionUpdateService.class);
        intent.putExtra("appName", "redvip" + System.currentTimeMillis());
        intent.putExtra("updateUrl", url);
        context.startService(intent);
    }
 
	 /**
     * 检查是否存在SDCard
     * @return
     */
    public static boolean hasSdcard(){
            String state = Environment.getExternalStorageState();
            if(state.equals(Environment.MEDIA_MOUNTED)){
                    return true;
            }else{
                    return false;
            }
    }
    
    /**
	 * 获取内置SD卡路径
	 * @return
	 */
	public static String getInnerSDCardPath() {  
        return Environment.getExternalStorageDirectory().getPath();  
    }
	
	
	
    /**
	 * 获取外置SD卡路径
	 * @return	应该就一条记录或空
	 */
	public static List getExtSDCardPath()
	{
		List lResult = new ArrayList();
		try {
			Runtime rt = Runtime.getRuntime();
			Process proc = rt.exec("mount");
			InputStream is = proc.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line;
			while ((line = br.readLine()) != null) {
				if (line.contains("extSdCard"))
				{
					String [] arr = line.split(" ");
					String path = arr[1];
					File file = new File(path);
					if (file.isDirectory())
					{
						lResult.add(path);
					}
				}
			}
			isr.close();
		} catch (Exception e) {
		}
		return lResult;
	}
	
	
	 public static String getSDPath() throws Exception {
	        try {

	        } catch (Exception e) {
	            throw e;
	        }
	        File sdDir = null;
	        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
	        if (sdCardExist) {
	            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
	        }
	        return sdDir.toString();

	    }
	
	 /**
     * 保存到SD卡
     *
     * @param filename
     * @param filecontent
     * @throws Exception
     */
    public static void saveStringToSDCard(String filename, String filecontent) throws Exception {
        File file = new File(Environment.getExternalStorageDirectory(), filename);
        FileOutputStream outStream = new FileOutputStream(file);
        outStream.write(filecontent.getBytes());
        outStream.close();
    }
    
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            // 关闭流
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }
    
    public static List<File> copeFiles(List<File> files) {
        List<File> copeFiles = new ArrayList<File>();
        String tempPath = "";
        for (File file : files) {
            if (TextUtils.isEmpty(tempPath)) {
                tempPath = Constants.SAVE_IMAGE_PATH_IMGS + System.currentTimeMillis() + "/";
            }
            File path = new File(tempPath);
            if (!path.exists()) {
                path.mkdirs();
            }
            String copeFilePath = path.getPath() + "/" + System.currentTimeMillis() + file.getPath().substring(file.getPath().lastIndexOf("."));
            File copeFile = new File(copeFilePath);
            try {
                AppUtils.copyFile(file, copeFile);
                copeFiles.add(copeFile);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return copeFiles;
    }
    
    public static File copeFile(File file) {
        String tempPath = Constants.SAVE_IMAGE_PATH_IMGS + System.currentTimeMillis() + "/";
        File path = new File(tempPath);
        if (!path.exists()) {
            path.mkdirs();
        }
        String copeFilePath = path.getPath() + "/" + System.currentTimeMillis() + file.getPath().substring(file.getPath().lastIndexOf("."));
        File copeFile = new File(copeFilePath);
        try {
            AppUtils.copyFile(file, copeFile);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return copeFile;
    }
    
    public static String removeFileHeader(String fileName) {
        try {
            if (fileName.startsWith("file:///")) {
                fileName = fileName.substring(7);
            }
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public static boolean isLocalImg(String img) {
        if (TextUtils.isEmpty(img)) {
            return false;
        }
        return img.startsWith("file:///");
    }

    public static String getFileName(String fileName) {
        try {
            if (fileName.startsWith("file:///")) {
                fileName = fileName.substring(7);
            }
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
            Track.d(fileName);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return fileName;
        }
    }
    
    
    final static String ATTRIBUTE_FILE_NAME = "att.property";

    public static void deleteAllFiles(File file) {
        if (file.exists() && file.isDirectory()) {
            boolean result = false;
            if (!(result = file.delete())) {
                File subs[] = file.listFiles();
                for (int i = 0; i < subs.length; i++) {
                    if (subs[i].isDirectory()) {
                        deleteAllFiles(subs[i]);
                    } else {
                        result = subs[i].delete();
                    }
                }
                result = file.delete();
            }
        }
        if (file.exists() && !file.getName().equals(ATTRIBUTE_FILE_NAME))
            file.delete();
    }
    
    public static Bitmap getBitmapWithWidth(Bitmap bitmap, int screenWidth) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scale = (float) screenWidth / w;

        // scale = scale < scale2 ? scale : scale2;

        // 保证图片不变形.
        matrix.postScale(scale, scale);
        // w,h是原图的属性.
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }

    public static Bitmap getBitmapWithHeight(Bitmap bitmap, int screenHight) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scale2 = (float) screenHight / h;

        // scale = scale < scale2 ? scale : scale2;

        // 保证图片不变形.
        matrix.postScale(scale2, scale2);
        // w,h是原图的属性.
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }

    public static Bitmap getBitmapWithFullScreen(Bitmap bitmap, int screenWidth, int screenHight) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Log.e("jj", "图片宽度" + w + ",screenWidth=" + screenWidth);
        Matrix matrix = new Matrix();
        float scale = (float) screenWidth / w;
        float scale2 = (float) screenHight / h;

        // scale = scale < scale2 ? scale : scale2;

        // 保证图片不变形.
        matrix.postScale(scale, scale2);
        // w,h是原图的属性.
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }

    public static void saveBitmap(String path, String bitmapName, Bitmap mBitmap) {
        File pathFile = new File(path);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        File f = new File(path + bitmapName);
        try {
            if (f.exists()) {
                f.delete();
            }
            f.createNewFile();
        } catch (Exception e) {
            System.out.println("在保存图片时出错");
            e.printStackTrace();
            return;
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Bitmap getBitmapFromRes(Context context, int Res) {
        return BitmapFactory.decodeResource(context.getResources(), Res).copy(Bitmap.Config.ARGB_4444, true);
    }

    public static Bitmap getBitmapFromResLow(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    public static void saveBitmap2SDcard(String bitName, Bitmap mBitmap) throws Exception {

        File f = new File(getSDPath() + "/" + bitName + ".png");
        try {
            f.createNewFile();
        } catch (IOException e) {
            // MAMessage.ShowMessage(context, "MSG",
            // "在保存图片时出错：" + e.toString());
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    /**
     * 调用浏览器跳转到指定网页
     *
     * @param context
     * @param url
     */
    public static void startBrowser(Context context, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        context.startActivity(intent);
    }

    /**
     * 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
     * @param context
     * @return
     */
    public static boolean isNetWorkAvailable(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    // 判断当前网络是否已经连接
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            Log.v("error", e.toString());
        }
        return false;
    }

    /**
     * 获取当前网络的名字
     *
     * @param activity
     * @return
     */
    public static String getCurrentNetWorkName(Activity activity) {

        ConnectivityManager cwjManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);

        cwjManager.getActiveNetworkInfo();

        if (cwjManager.getActiveNetworkInfo() != null) {
            return cwjManager.getActiveNetworkInfo().getTypeName();
        }
        return "";

    }
    
    /*
     * 为照片命名
     */
    public static String getStringToday() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }
    
    /**
     * 拍照
     *
     * @param imageName   文件名称,例如:"ier2222.jpg"
     * @param requestCode startActivityForResult的请求参数
     */
    public static void tackPic(Activity activity, String imageName, int requestCode) {
        try {
            if (!AppUtils.isSDUseable()) {
                Toast.makeText(activity, "SD卡不可用,无法拍照", 1000).show();
                return;
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            File file = new File(Constants.APP_FILE_DIR, imageName);
            if (file.exists()) {
                file.delete();
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
            activity.startActivityForResult(intent, requestCode);
        } catch (Exception e) {
            Toast.makeText(activity, "打开相机失败", 1000).show();
            e.printStackTrace();
        }
    }


    /**
     * 拍照
     *
     * @param imageName   文件名称,例如:"ier2222.jpg"
     * @param requestCode startActivityForResult的请求参数
     */
    public static void tackPic(Fragment fragment, String imageName, int requestCode) {
        try {
            if (!AppUtils.isSDUseable()) {
                Toast.makeText(fragment.getActivity(), "SD卡不可用,无法拍照", 1000).show();
                return;
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            File file = new File(Constants.APP_FILE_DIR, imageName);
            if (file.exists()) {
                file.delete();
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
            fragment.startActivityForResult(intent, requestCode);
        } catch (Exception e) {
            Toast.makeText(fragment.getActivity(), "打开相机失败", 1000).show();
            e.printStackTrace();
        }
    }


    /**
     * 拍照返回处理
     *
     * @param imageName
     * @param handler
     */
    public static void tackPickResult(final String imageName, final Handler handler) {

        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 压缩照片
                        File file = new File(Constants.APP_FILE_DIR, imageName);
                        ImageHelper.saveCompressBitmap(file);
                        Message message = new Message();
                        message.what = Constants.PHOTO_COMPASS_SUCCESS;
                        message.obj = Constants.APP_FILE_DIR + "/" + imageName;
                        handler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从相册选择单张图片
     *
     * @param activity
     * @param requestCode
     */
    public static void chooseSinglePhoto(Activity activity, int requestCode) {
        try {
            Intent intent1 = new Intent(Intent.ACTION_PICK, null);
            intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            activity.startActivityForResult(intent1, requestCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void chooseSinglePicResult(Activity activity, Handler handler, Intent data) {
        Uri originalUri = data.getData();
        // 获得图片的uri
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.managedQuery(originalUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        Message message = new Message();
        message.what = Constants.CHOOSE_SINGLE_PHOTO_SUCCESS;
        message.obj = path;
        handler.sendMessage(message);
    }

    /**
     * 跳转到图片详情
     *
     * @param activity
     * @param position     当前图片位置
     * @param paths        所有图片路径
     * @param 图片详情页面是否可以删除
     */
    public static void toImageDetial(Activity activity, int position, List<String> paths, boolean deleteable) {
        try {
            Intent intent = new Intent(activity, ImageBrowserActivity.class);
            intent.putExtra("paths", (Serializable) paths);
            intent.putExtra("position", position);
            intent.putExtra("deleteable", deleteable);
            activity.startActivityForResult(intent, Constants.IMAGEDITAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到图片详情
     *
     * @param activity
     * @param position     当前图片位置
     * @param paths        所有图片路径
     * @param 图片详情页面是否可以删除
     */
    public static void toImageDetial(Activity activity, int position, List<String> paths, EditImageReciver editImageReciver) {
        try {
            IntentFilter intentFilter = new IntentFilter(Constants.EDIT_IMG_REQCODE);
            activity.registerReceiver(editImageReciver, intentFilter);

            Intent intent = new Intent(activity, ImageBrowserActivity.class);
            intent.putExtra("paths", (Serializable) paths);
            intent.putExtra("position", position);
            intent.putExtra("deleteable", true);
            activity.startActivityForResult(intent, Constants.IMAGEDITAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到图片详情
     *
     * @param context
     * @param position 从0开始
     * @param paths
     */
    public static void toImageDetial(Context context, int position, List<String> paths) {
        try {
            Intent intent = new Intent(context, ImageBrowserActivity.class);
            intent.putExtra("paths", (Serializable) paths);
            intent.putExtra("position", position);
            intent.putExtra("deleteable", false);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void toImageDetial(Context context, List<String> paths) {
        try {
            Intent intent = new Intent(context, ImageBrowserActivity.class);
            intent.putExtra("paths", (Serializable) paths);
            intent.putExtra("deleteable", false);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取版本号(内部识别号)
     * @param context
     * @return
     */
    public static int getVersionCode(Context context){
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    
    public static void showKeyBorad(Context context, View view) {
        try {
            if (context == null)
                return;
            view.requestFocus();
            InputMethodManager manager = ((InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE));
            manager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void hideKeyBorad(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 强制隐藏键盘
    }
}
